import type { IMarkerIconExposedProps, IPoi, IPoiExt } from "@/common/MapTypes";
import { defineStore } from "pinia";
import { reactive } from "vue";
import * as markerApi from "@/api/markerApi";
import { ResponseCode, type IResponseBody } from "@/common/Responsetypes";

export interface IMarkerState {
  activeMarker: null | IMarkerIconExposedProps;
  markers: IPoiExt[]; // 用户所有的 marker，
  extraMarkers: IPoiExt[]; // 其他用户的 marker
  activeMarkerExtra: null | IMarkerIconExposedProps; // 当前激活的其他用户的 marker
}

export const useMarkerStore = defineStore("marker", () => {
  const state: IMarkerState = reactive({
    activeMarker: null, // 当前激活的marker
    markers: [], // 用户所有的 marker
    extraMarkers: [],
    activeMarkerExtra: null,
  });

  function setActiveMarker(marker: IMarkerIconExposedProps | null) {
    if (state.activeMarker) {
      state.activeMarker?.setActive?.(false);
    }
    state.activeMarker = marker;
    state.activeMarker?.setActive?.(true);
  }

  function getActiveMarker() {
    return state.activeMarker;
  }

  function getMarkers() {
    return state.markers;
  }

  function setMarkers(markers: IPoiExt[]) {
    state.markers = markers;
  }

  async function addMarker(marker: IPoi): Promise<IResponseBody<object>> {
    return new Promise((resolve) => {
      if (markerIsExist(marker)) {
        resolve({
          code: ResponseCode.ERROR,
          msg: "该标记已存在",
          data: {},
        });
      } else {
        uni.showLoading();
        markerApi.add(marker).then((result) => {
          if (result.code === ResponseCode.PASS) {
            state.markers.push(result.data as IPoiExt);
          }
          uni.hideLoading();
          resolve(result);
        });
      }
    });
  }

  async function removeMarker(marker: IPoi): Promise<IResponseBody<object>> {
    return new Promise((resolve) => {
      const index = state.markers.findIndex((m) => m.id === marker.id);
      if (index > -1) {
        uni.showLoading();
        markerApi.del(marker.id).then((result) => {
          if (result.code === ResponseCode.PASS) {
            state.markers.splice(index, 1);
            setActiveMarker(null);
          }
          uni.hideLoading();
          resolve(result);
        });
      }
    });
  }

  function markerIsExist(marker: IPoi) {
    return state.markers.some((m) => m.id === marker.id);
  }

  return {
    setActiveMarker,
    getActiveMarker,
    state,
    getMarkers,
    setMarkers,
    addMarker,
    removeMarker,
    markerIsExist,
  };
});
